package com.example.asd.puzzle;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.List;

import puzzle.Puzzle;

public class MainActivity extends AppCompatActivity {
    public static String str_nick, str_myip, str_server,TAG="TAG";
    private TextView tv_onlineNum,tv_mIP,tv_mNick;
    private Button bt_createRoom,bt_refresh;
    private int onlineNum=0;
    private ListView lv_roomList;
    private ArrayAdapter<String> arrayAdapter;
    private List<String> strings_roomList=new ArrayList<>();
    private Handler handler=new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1){
                case 0://Toast
                    Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                    break;
                case 1://Msg received
                    handleMsgFromPushServer((JSONObject)msg.obj);
                    break;
                case 2://Update OnlineNUm
                    onlineNum=msg.arg2;
                    tv_onlineNum.setText("当前在线人数："+onlineNum);
                    break;
                case 3://Update roomList
                    JSONArray array=(JSONArray)msg.obj;
                    strings_roomList.clear();
                    try {
                        for(int i=0;i<array.length();i++){
                            strings_roomList.add(array.getJSONObject(i).getString("Name"));
                        }
                        arrayAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 4://enter room
                    Intent intent=new Intent(MainActivity.this,RoomWaitingActivity.class);
                    intent.putExtra("roomName",msg.obj.toString());
                    startActivity(intent);
                    break;
            }
        }
    };

    private void handleMsgFromPushServer(JSONObject obj) {
        try {
            String state=obj.getString("State");
            switch (state){
                case "online":
                    apis_getOnlineNum();
                    break;
                case "offline":
                    apis_getOnlineNum();
                    break;
                case "createRoom":
                    apis_getRoomList();
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void apis_getRoomList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String str=Puzzle.doRequest("http://"+str_server+":8080/apis/getallrooms","");
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")){
                        JSONArray jsonArray=o.getJSONArray("Data");
                        Message message=new Message();
                        message.arg1=3;
                        message.obj=jsonArray;
                        handler.sendMessage(message);
                    }else{
                        Log.d(TAG, "run: getRoomList() failed :"+o.getString("Info").toString());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void apis_getOnlineNum() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String str=Puzzle.doRequest("http://"+str_server+":8080/apis/getonlinenum","");
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")) {
                        int num = Integer.parseInt(o.getString("Info").toString());
                        Message message = new Message();
                        message.arg1 = 2;
                        message.arg2 = num;
                        handler.sendMessage(message);
                    }else {
                        toastMe(o.getString("Info".toString()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void apis_joinRoom(final String str_roomName){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    String str=Puzzle.doRequest("http://"+str_server+":8080/apis/joinroom",new JSONObject().put("Info",str_roomName).toString());
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")) {
                        Message message = new Message();
                        message.arg1 = 4;
                        message.obj = str_roomName;
                        handler.sendMessage(message);
                    }else if (o.getString("State").toString().equals("ERR")&&o.getString("Info").toString().equals("Room is gaming")){
                        toastMe("此房间正在游戏中");
                    }else{
                        Log.d(TAG, "run: getRoomList() failed :"+o.getString("Info").toString());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private PushService.MyBinder binder;
    private OnMsgReceivedListener listener=new OnMsgReceivedListener() {
        @Override
        public void onMsgReceived(JSONObject str) {
            Message message=new Message();
            message.arg1=1;
            message.obj=str;
            handler.sendMessage(message);
        }
        @Override
        public void toastMe(String str) {
            toastMe(str);
        }
    };
    private ServiceConnection sc=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            binder=(PushService.MyBinder)iBinder;
            binder.setListener(listener);
            apis_getRoomList();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        apis_getRoomList();
        if (binder!=null)
            binder.setListener(listener);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent gintent=getIntent();
        str_nick =gintent.getStringExtra("nick");
        str_myip = Puzzle.getIP();
        str_server =gintent.getStringExtra("server");
        initUI();
        netConnection();
    }

    private void netConnection() {
        Intent intent=new Intent(MainActivity.this,PushService.class);
        bindService(intent,sc,BIND_AUTO_CREATE);
    }
    private void toastMe(String data){
        Message message=new Message();
        message.arg1=0;
        message.obj=data;
        handler.sendMessage(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binder.setRunningFlag(false);
        unbindService(sc);
    }

    private void initUI() {
        tv_onlineNum=findViewById(R.id.main_tv_onlineNum);
        tv_mIP=findViewById(R.id.main_tv_mIP);
        tv_mNick=findViewById(R.id.main_tv_mNick);
        bt_createRoom=findViewById(R.id.main_bt_createRoom);
        lv_roomList=findViewById(R.id.main_lv_roomList);
        bt_refresh=findViewById(R.id.main_refresh);

        tv_mNick.setText("我的昵称："+ str_nick);
        tv_mIP.setText("我的IP:"+ str_myip);
        bt_createRoom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final EditText editText=new EditText(MainActivity.this);
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("输入房间名")
                        .setView(editText)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String roomName=editText.getText().toString();
                                createRoom(roomName);
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.cancel();
                            }
                        })
                        .show();
            }
        });
        arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,strings_roomList);
        lv_roomList.setAdapter(arrayAdapter);
        lv_roomList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                apis_joinRoom(strings_roomList.get(i));
            }
        });
        bt_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                apis_getOnlineNum();
                apis_getRoomList();
            }
        });
    }

    private void createRoom(final String roomName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String str=Puzzle.doRequest("http://"+str_server+":8080/apis/createroom",new JSONObject().put("Info",roomName).toString());
                    JSONObject o=(JSONObject)(new JSONTokener(str).nextValue());
                    if (o.getString("State").toString().equals("OK")) {
                        Message message = new Message();
                        message.arg1 = 4;
                        message.obj=roomName;
                        handler.sendMessage(message);
                    }else {
                        toastMe(o.getString("Info".toString()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
